package service;

import dao.UsersDao;
import domin.Actor;
import domin.Users;
import lombok.extern.slf4j.Slf4j;
import util.Condition;
import util.JWTHelper;
import util.JdbcHelper;
import util.Pagination;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashMap;
@Slf4j
public final class UsersService {
    private UsersDao usersDao = UsersDao.getInstance();
    private static UsersService usersService = new UsersService();

    public UsersService() {
    }

    public static UsersService getInstance(){
        return UsersService.usersService;
    }

    public Collection<Users> findAll(Collection<Condition> conditions , Pagination pagination) throws SQLException {
        Connection connection = JdbcHelper.getConn();
        Collection<Users> users = usersDao.findAll(connection,conditions,pagination);
        JdbcHelper.close(connection);
        return users;
    }

    public Users getUser(Integer id) throws SQLException {
        Connection connection = JdbcHelper.getConn();
        Users user = UsersDao.getInstance().find(connection,id);
        JdbcHelper.close(connection);
        return user;
    }

    public boolean update(Users user) throws SQLException {
        boolean updated =false;
        Connection connection = JdbcHelper.getConn();
        connection.setAutoCommit(false);
        try {
        updated = usersDao.update(connection,user);
            connection.commit();
        } catch (SQLException e) {
            connection.rollback();
        } finally {
            connection.setAutoCommit(true);
            JdbcHelper.close(connection);
        }
        return updated;
    }

    public boolean add(Users user) throws SQLException {
        boolean added = false;
        Connection connection = JdbcHelper.getConn();
        connection.setAutoCommit(false);
        try {
            added = usersDao.add(connection, user);
            connection.commit();
        } catch (SQLException e) {
            connection.rollback();
        } finally {
            connection.setAutoCommit(true);
            JdbcHelper.close(connection);
        }
    return added;
    }

    public boolean delete(Integer id) throws SQLException {
        Connection connection = JdbcHelper.getConn();
        boolean deleted = usersDao.delete(connection,id);
        JdbcHelper.close(connection);
        return deleted;
    }
    public Actor login(Users userToLogin) throws SQLException {
        HashMap<String,String> payload = new HashMap<>();
        payload.put("username",userToLogin.getUsername());
        payload.put("password",userToLogin.getPassword());
        Connection connection = JdbcHelper.getConn();
        Actor actor = usersDao.login(connection, userToLogin);
        JdbcHelper.close(connection);
        return actor;
    }
}
